package com.pxst.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import com.google.code.kaptcha.Producer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pxst.resp.ApiResp;
import com.pxst.resp.AuthCodeResp;
import com.pxst.utils.RedisUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/** 
* @author yangxy
* @version 创建时间：2023年7月26日 下午5:06:37 
*/
@RestController
@RequestMapping("/sys/common")
@Api(tags = "公共接口")
public class CommonController {
	@Autowired
	private RedisUtils redisUtils;

    @Resource
    private Producer producer;
	
    @GetMapping("/authCode")
	@SuppressWarnings("unchecked")
    @ApiOperation(value = "获取图形验证码")
	public ApiResp<AuthCodeResp> authCode() throws IOException{
		String uuid = UUID.randomUUID().toString();
        //生成文字验证码
        String text = producer.createText();
 
        //个位数字相加
        String s1 = text.substring(0, 1);
        String s2 = text.substring(1, 2);
        int count = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
 
        redisUtils.set(uuid, count, 20);
        //生成图片验证码
        BufferedImage image = producer.createImage(s1 + "+" + s2 + "=?");
 
        //保存 redis key 自己设置
        //stringRedisTemplate.opsForValue().set("",String.valueOf(count));
 
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", bos);

        byte[] bytes = bos.toByteArray();
        Base64.Encoder encoder = Base64.getEncoder();
        String base64String = encoder.encodeToString(bytes);
        AuthCodeResp authCodeDto = new AuthCodeResp();
        authCodeDto.setUrl("data:image/png;base64,"+base64String);
        authCodeDto.setUuid(uuid);
        return ApiResp.sucess(authCodeDto);
	}
}
